package com.koi.system.service.dictdata;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koi.common.constants.KoiCacheConstants;
import com.koi.common.constants.KoiConstants;
import com.koi.common.redis.RedisUtil;
import com.koi.plus.mapper.system.SysDictDataMapper;
import com.koi.plus.mapper.system.SysDictTypeMapper;
import com.koi.pojo.system.SysDictData;
import com.koi.pojo.system.SysDictType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ･ᴗ･
 * @description [字典数据表-服务实现层]
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {

    private final SysDictDataMapper sysDictDataMapper;

    private final SysDictTypeMapper sysDictTypeMapper;

    private final RedisUtil redisUtil;


    /**
     * @description [字典数据同步Redis进行缓存]
     * @author ･ᴗ･
     */
    @Override
    public void listDictCacheRedis() {
        // 1、查询所有可用的字典数据
        LambdaQueryWrapper<SysDictType> dictTypeWrapper = new LambdaQueryWrapper<>();
        dictTypeWrapper.select(SysDictType::getDictType, SysDictType::getDictStatus);
        List<SysDictType> dictTypeList = sysDictTypeMapper.selectList(dictTypeWrapper);
        if(CollectionUtil.isNotEmpty(dictTypeList)){
            // 2、根据字典类型查询字典数据
            for (SysDictType sysDictType : dictTypeList) {
                if(sysDictType.getDictStatus().equals(KoiConstants.ZERO_STRING)){
                    LambdaQueryWrapper<SysDictData> dictDataWrapper = new LambdaQueryWrapper<>();
                    dictDataWrapper.eq(SysDictData::getDictStatus, KoiConstants.ZERO_STRING);
                    dictDataWrapper.eq(SysDictData::getDictType, sysDictType.getDictType());
                    dictDataWrapper.orderByAsc(SysDictData::getSorted);
                    List<SysDictData> dictDataList = sysDictDataMapper.selectList(dictDataWrapper);
                    // 3、把字典数据循环存到Redis，设计Redis的key：koiDict:dictType -> [{},{},{}]
                    redisUtil.setCacheObject(KoiCacheConstants.DICT_REDIS_KEY + sysDictType.getDictType(), dictDataList);
                }else {
                    redisUtil.deleteKey(KoiCacheConstants.DICT_REDIS_KEY + sysDictType.getDictType());
                }
            }
        }
    }

}
